import json
import os
import random
import time

import requests
from django.contrib import admin
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME

from django.http import HttpResponse
from django.utils.html import format_html

from database import models
from utils.requests_pro import find_province, get_page, run_mains

# Register your models here.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
from openpyxl import Workbook




class Total(admin.ModelAdmin):

    list_display = ('jobName', 'boss_picture',"brandName", "wages", "bossName", "bossTitle", "jobExperience",
                    "jobDegree", "skills","cityName", "province", "areaDistrict", "brandStageName",
                    "brandIndustry", "brandScaleName", "welfareList", "href_link","collection")

    search_fields = ('jobName',"brandName",)
    list_per_page = 20
    actions = ["export_as_excel","fc_request_data" ]

    # 公司封面
    def boss_picture(self, models_obj):
        return format_html('<img src="{}" height="50" width="50">', '{}'.format(models_obj.brandLogo))
    boss_picture.short_description = '公司LOGO'

    def changelist_view(self, request, extra_context=None):
        if 'action' in request.POST and request.POST['action'].startswith('fc_'):
            if not request.POST.getlist(ACTION_CHECKBOX_NAME):
                post = request.POST.copy()
                for u in models.Total.objects.all():
                    post.update({ACTION_CHECKBOX_NAME: str(u.id)})
                request.POST = post
        return super(Total, self).changelist_view(request, extra_context)

    def export_as_excel(self, request, queryset):

        meta = self.model._meta  # 用于定义文件名, 格式为: app名.模型类名
        field_names = [field.name for field in meta.fields]  # 模型所有字段名
        response = HttpResponse(content_type='application/msexcel')  # 定义响应内容类型
        response['Content-Disposition'] = f'attachment; filename={meta}.xlsx'  # 定义响应数据格式
        wb = Workbook()  # 新建Workbook
        ws = wb.active  # 使用当前活动的Sheet表
        ws.append(field_names)  # 将模型字段名作为标题写入第一行
        for obj in queryset:  # 遍历选择的对象列表
            for field in field_names:
                data = [f'{getattr(obj, field)}' for field in field_names]  # 将模型属性值的文本格式组成列表
            ws.append(data)
        wb.save(response)
        return response
    export_as_excel.short_description = '导出Excel'  # 该动作在admin中的显示文字
    export_as_excel.type = 'primary'
    export_as_excel.icon = 'el-icon-download'


    # 爬取岗位
    def fc_request_data(self, request, queryset):
        try:
            city_code = "100010000"
            start_page = 1
            stop_page = 5

            session = requests.Session()
            cookies = str(models.Cookies.objects.last().cookies).replace(" ", "")
            headers = {
                "cookie": cookies,
                "referer": "https://www.zhipin.com/web/geek/job?query=&city=100010000&page=1",
                "user-agent": "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"
            }
            for _ in range(start_page, stop_page + 1):
                try:
                    page = session.get(
                        url="https://www.zhipin.com/wapi/zpgeek/search/joblist.json?scene=1&query=&city={}&experience=&degree=&industry=&scale=&stage=&position=&jobType=&salary=&multiBusinessDistrict=&multiSubway=&page={}&pageSize=30".format(
                            city_code, _), headers=headers)
                    json_data = eval(page.text.replace("true", "1").replace("false", "2").replace("null", "0"))
                    for obj in json_data.get('zpData').get('jobList'):
                        brandLogo = obj.get('brandLogo')  # 公司LOGO
                        brandName = obj.get('brandName')  # 公司名称
                        url = "https://www.zhipin.com/job_detail/{}.html".format(obj.get('encryptJobId'))  # 详情
                        # 工资
                        salaryDesc_raw = obj.get('salaryDesc')  # 工资
                        wages = float(str(salaryDesc_raw).split("-")[0].replace("千", ""))
                        if 1 <= wages < 3:
                            salaryDesc = wages * 10000
                        if 3 <= wages <= 9:
                            salaryDesc = wages * 1000
                        if wages > 10:
                            salaryDesc = int(str(int((wages * 10000) / 12))[0:2] + "000")
                        if salaryDesc > 20000:
                            salaryDesc = float(str(salaryDesc / 5)[0:2] + "00")

                        bossName = obj.get('bossName')  # 招聘人
                        bossTitle = obj.get('bossTitle')  # 招聘人职位
                        jobName = obj.get('jobName')  # 招聘职位
                        jobExperience = obj.get('jobExperience')  # 需求经验
                        jobDegree = obj.get('jobDegree')  # 学历
                        skills = ",".join(obj.get('skills'))  # 掌握技能
                        cityName = obj.get('cityName')  # 城市
                        province = find_province(cityName)  # 省份
                        areaDistrict = obj.get('areaDistrict')  # 区域
                        brandStageName = obj.get('brandStageName')  # 融资情况
                        brandIndustry = obj.get('brandIndustry')  # 公司分类
                        brandScaleName = obj.get('brandScaleName')  # 公司规模
                        welfareList = ",".join(obj.get('welfareList'))  # 福利
                        print("岗位：{} 正在入库".format(jobName))
                        if models.Total.objects.filter(jobName=jobName).exists() == False:
                            models.Total.objects.create(brandLogo=brandLogo, brandName=brandName, url=url,
                                                        wages=salaryDesc,
                                                        bossName=bossName, bossTitle=bossTitle, skills=skills,
                                                        jobName=jobName, jobExperience=jobExperience,
                                                        jobDegree=jobDegree,
                                                        cityName=cityName, province=province,
                                                        areaDistrict=areaDistrict,
                                                        brandStageName=brandStageName, brandIndustry=brandIndustry,
                                                        brandScaleName=brandScaleName, welfareList=welfareList)
                except:
                    pass
            return HttpResponse("爬取成功，请刷新页面")

        except Exception as e:
            return HttpResponse("爬取失败，失败原因:{},请联系管理员处理(QQ995405033)".format(e), )
    fc_request_data.short_description = '爬取岗位'
    fc_request_data.type = 'success'
    fc_request_data.icon = 'el-icon-s-promotion'



admin.site.register(models.Total, Total)






@admin.register(models.CityMsg)
class CityMsg(admin.ModelAdmin):
    list_display = ('name','code',)

    actions = ["fc_request_data"]

    def changelist_view(self, request, extra_context=None):
        if 'action' in request.POST and request.POST['action'].startswith('fc_'):
            if not request.POST.getlist(ACTION_CHECKBOX_NAME):
                post = request.POST.copy()
                for u in models.CityMsg.objects.all():
                    post.update({ACTION_CHECKBOX_NAME: str(u.id)})
                request.POST = post
        return super(CityMsg, self).changelist_view(request, extra_context)


    # 爬取数据
    def fc_request_data(self, request, queryset):
        try:
            session = requests.Session()
            headers = {
                "referer": "https://www.zhipin.com/web/geek/job?query=&city=100010000&page=1",
                "user-agent": "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"
            }
            page = session.get(url="https://www.zhipin.com/wapi/zpgeek/common/data/citysites.json", headers=headers)
            for obj in page.json().get('zpData'):
                try:
                    city_code = obj.get('code')
                    city_name = obj.get('name')
                    if models.CityMsg.objects.filter(name=city_name).exists() == False:
                        models.CityMsg.objects.create(name=city_name,code=city_code)
                except:
                    pass
            return HttpResponse("爬取成功，请刷新页面")

        except Exception as e:
            return HttpResponse("爬取失败，失败原因:{},请联系管理员处理(QQ995405033)".format(e), )
    fc_request_data.short_description = '更新城市代码'
    fc_request_data.type = 'success'
    fc_request_data.icon = 'el-icon-s-promotion'






@admin.register(models.Cookies)
class Cookies(admin.ModelAdmin):

    list_display = ("cookies",)

    # 定义
    def get_form(self, request, obj=None, **kwargs):
        form = super(Cookies, self).get_form(request, obj, **kwargs)
        form.base_fields['cookies'].widget.attrs['style'] = 'width: 1000px;'  # link 字段名
        return form






class Colect(admin.ModelAdmin):   # 这里需要修改

    list_display = ("co_title","co_down_link","href_link")
    list_filter = ["co_title","co_down_link"]
    list_per_page = 20
    actions = ["export_as_excel"]

    def export_as_excel(self, request, queryset):
        meta = self.model._meta  # 用于定义文件名, 格式为: app名.模型类名
        field_names = [field.name for field in meta.fields]  # 模型所有字段名
        response = HttpResponse(content_type='application/msexcel')  # 定义响应内容类型
        response['Content-Disposition'] = f'attachment; filename={meta}.xlsx'  # 定义响应数据格式
        wb = Workbook()  # 新建Workbook
        ws = wb.active  # 使用当前活动的Sheet表
        ws.append(field_names)  # 将模型字段名作为标题写入第一行
        for obj in queryset:  # 遍历选择的对象列表
            for field in field_names:
                data = [f'{getattr(obj, field)}' for field in field_names]  # 将模型属性值的文本格式组成列表
            ws.append(data)
        wb.save(response)
        return response
    export_as_excel.short_description = '导出Excel'  # 该动作在admin中的显示文字
admin.site.register(models.Colect, Colect)  # 这里需要修改





admin.site.site_title="BOSS直聘互联网相关职业数据分析"
admin.site.site_header="BOSS直聘互联网相关职业数据分析"
admin.site.index_title="BOSS直聘互联网相关职业数据分析"
